package com.ifacebox.face.track.ui;

import com.github.sarxos.webcam.Webcam;

import java.awt.Component;
import javax.swing.*;
import java.util.List;
import java.util.Objects;

/**
 * @author znn
 */
public class FaceWebCamPicker extends JComboBox<Webcam> {
    private static final ImageIcon ICON = new ImageIcon(Objects.requireNonNull(FaceWebCamPicker.class.getResource("/com/github/sarxos/webcam/icons/camera-icon.png")));

    public FaceWebCamPicker(List<Webcam> webcams) {
        super.setModel(new WebCamPickerModel(webcams));
        super.setRenderer(new WebCamPickerCellRenderer());
    }

    public Webcam getSelectedWebcam() {
        return (Webcam) this.getSelectedItem();
    }

    static class WebCamPickerModel extends DefaultComboBoxModel<Webcam> {
        public WebCamPickerModel(List<Webcam> webcams) {
            super(webcams.toArray(new Webcam[0]));
        }

        @Override
        public Webcam getSelectedItem() {
            return (Webcam) super.getSelectedItem();
        }

        @Override
        public void setSelectedItem(Object webcam) {
            if (webcam instanceof Webcam) {
                super.setSelectedItem(webcam);
            }
        }
    }

    static class WebCamPickerCellRenderer extends JLabel implements ListCellRenderer<Webcam> {
        public WebCamPickerCellRenderer() {
            super.setOpaque(true);
            super.setHorizontalAlignment(LEFT);
            super.setVerticalAlignment(CENTER);
            super.setIcon(ICON);
        }

        @Override
        public Component getListCellRendererComponent(JList<? extends Webcam> list, Webcam value, int index, boolean selected, boolean focus) {
            super.setBackground(selected ? list.getSelectionBackground() : list.getBackground());
            super.setForeground(selected ? list.getSelectionForeground() : list.getForeground());
            super.setText(value.getName());
            super.setFont(list.getFont());
            return this;
        }
    }
}
